<template>
  <div>
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body @close="cancel">
      <div class="text-center mb20" v-if="!configId">
        <el-radio-group v-model="evaluationRadio" size="small">
          <el-radio label="5" border>整体测评</el-radio>
          <el-radio label="51" border>单品测评</el-radio>
          <el-radio label="52" border>指定日期测评</el-radio>
        </el-radio-group>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="测评名称" prop="evaluationName">
          <el-input v-model="form.evaluationName" size="small" placeholder="请输入测评名称"/>
        </el-form-item>
        <el-form-item label="测评国家" prop="evaluationCountry">
          <el-select v-model="form.evaluationCountry" placeholder="请选择国家" clearable filterable multiple
                     style="width: 700px">
            <el-option v-for="dict in dict.type.sys_evaluation_country" :key="dict.value" :label="dict.label"
                       :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否开启随机备注" prop="randomRemark">
          <el-radio-group v-model="form.randomRemark">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="evaluationRadio=='52'">
          <el-form-item label="测评时间" prop="evaluationConfigTaskList">
            <div v-for="(item,index) in form.evaluationConfigTaskList" :key="index">
              <div class="flexBox mb10">
                <el-date-picker :disabled="form.id && isUseShareCode=='0'" @change="chooseEvaluationTime"
                                v-model="item.planStartTime"
                                type="datetime" placeholder="请选择时间" value-format="yyyy-MM-dd HH:mm:ss"
                                format="yyyy-MM-dd HH:mm:ss"/>
                <div class="ml10">
                  <el-input :disabled="form.id && isUseShareCode=='0'" placeholder="请输入测评单数"
                            v-model="item.planEvaluationNum"/>
                </div>
                <div class="ml20">
                  <el-button :disabled="form.id  && isUseShareCode=='0'" size="small" @click="addAllocation(item,index)"
                             type="primary"
                             icon="el-icon-plus" circle/>
                  <el-button :disabled="form.id && isUseShareCode=='0'" size="small" v-if="index != '0' "
                             @click="cutAllocation(item,index)"
                             type="danger"
                             icon="el-icon-minus" circle/>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="店铺测评条件1" prop="beforeDay">
            <el-input v-model="form.beforeDay" size="small" class="width4 ml10" placeholder="请输入">
              <template slot="prepend">测评近</template>
              <template slot="append">天出的自然订单</template>
            </el-input>
          </el-form-item>
        </div>

        <div v-if="evaluationRadio == '51'">
          <el-form-item label="单品测评条件1" prop="afterNumber">
            <el-input v-model="form.orderQuantity" class="width3" size="small"
                      placeholder="请输入数量">
              <template slot="prepend">单品出单达到</template>
              <template slot="append">单后</template>
            </el-input>
            <el-input class="width3 ml10" v-model="form.afterNumber" type="number" size="small"
                      placeholder="请输入">
              <template slot="prepend">第二天测评</template>
              <template slot="append">单本商品</template>
            </el-input>
          </el-form-item>
        </div>
        <div v-if="evaluationRadio !='51'">
          <el-form-item label="店铺测评条件1" prop="beforeDay" v-if="evaluationRadio=='5'">
            <el-input v-model="form.nullOrderDay" size="small" class="width2" placeholder="请输入天数">
              <template slot="append">日不出单</template>
            </el-input>
            <el-input v-model="form.beforeDay" size="small" class="width4 ml10" placeholder="请输入">
              <template slot="prepend">优先测评近</template>
              <template slot="append">天出的自然订单测评一单</template>
            </el-input>
          </el-form-item>
          <el-form-item label="店铺测评条件2" prop="sort">
            <div class="flex">
              <div v-for="(item,index) in dict.type.store_evaluation_sort" :key="index">
                <el-select v-model="storeSortData['storeSort'+index]" placeholder="请选择排序条件" clearable
                           size="small" style="width: 150px">
                  <el-option v-for="dict in dict.type.store_evaluation_sort" :key="dict.value" :label="dict.label"
                             :value="dict.value"/>
                </el-select>
                <span v-if="index != dict.type.store_evaluation_sort.length-1" class="ml5 mr5"> > </span>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="店铺测评条件3" prop="amountMax">
            <el-input class="width3" v-model="form.amountMin" size="small"
                      placeholder="请输入最小金额">
              <template slot="prepend">不低于</template>
              <template slot="append">元</template>
            </el-input>
            <el-input class="width35 ml10" v-model="form.amountMax" size="small" placeholder="请输入最大金额">
              <template slot="prepend">销售价格不超过</template>
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </div>
        <el-form-item label="刷单屏蔽商品ID" prop="shieldProductIds">
          <el-input v-model="form.shieldProductIds" size="small" placeholder="请输入速卖通id（逗号分割）"></el-input>
        </el-form-item>
        <el-form-item label="单品测评条件2" prop="isEvaluation">
          <el-checkbox v-model="form.isEvaluation">测评的上一个订单，不能是测评单</el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getBrand} from "@/api/gather/collectProduct";
import {saveEvaluationConfig, selectEvaluationConfig} from "@/api/autoOperation/evaluation";

export default {
  name: "grounding",
  dicts: ['sys_evaluation_country', 'store_evaluation_sort'],
  props: {
    storeId: {},
    configId: {
      type: String / Number,
      default: ""
    },
    userId: { // 绑定店铺的用户id
      type: String,
      default: ""
    },
    storeUserName: { //店铺账号 cn码
      type: String,
      default: ""
    },
    isUseShareCode: { // 是否使用分享码
      type: String,
      default: "0"
    },
    evaluationType: {
      type: String / Number,
      default: ""
    }
  },
  data() {
    return {
      buttonLoading: false,//确定提交表单按钮loading
      title: "新增测评配置",
      open: true,
      storeSortData: {},
      form: {},
      brandList: [],//品牌列表
      categoryList: [],//商品类目列表
      rules: {
        evaluationName: [{required: true, message: "测评名称不能为空", trigger: "blur"}],
        openTime: [{required: true, message: "请选择开启时间", trigger: "change"}],
        shieldProductIds: [{required: false, message: "请输入刷单屏蔽商品速卖通id", trigger: "blur"}],
        randomRemark: [{required: true, message: "请选择是否开启随机备注", trigger: "change"}],
        // startTime: [{required: true, message: "请选择测评时间", trigger: "change"}],
        evaluationConfigTaskList: [{required: true, validator: this.checkPlanTime, trigger: "change"}],
        orderQuantity: [
          {required: true, trigger: "change", message: "单品测评条件1不能为空"}],
        afterNumber: [
          {required: true, trigger: "change", message: "单品测评条件1不能为空"},
          {required: true, trigger: "change", validator: this.multipllCheck1}],
        beforeDay: [
          {required: true, message: "店铺测评条件1不能为空", trigger: "blur"},
          {validator: this.$Validate.isPositiveInteger,}],
        amountMax: [
          {required: true, trigger: "change", message: "店铺测评条件3不能为空",},
          {validator: this.$Validate.isPositiveInteger},
          {required: true, trigger: "change", validator: this.multipllCheck2}],
        evaluationMonthMax: [{required: true, message: '请输入每月最大测评单数量', trigger: 'blur'}],
        evaluationDayMax: [{required: true, message: '请输入每天最大测评单数量', trigger: 'blur'}],
      },
      evaluationRadio: "5",
    }
  },
  created() {
    this.evaluationRadio = this.evaluationType
    if (this.configId) {
      this.getConfigDetail()
    } else {
      this.reset()
    }
  },
  methods: {
    // 校验测评时间
    checkPlanTime(rule, value, callback) {
      console.log('value', value)
      value.forEach(item => {
        if (!item.planStartTime || !item.planEvaluationNum) {
          callback(new Error("请先完善测评时间或测评单数！"));
          return
        } else {
          callback()
        }
      })
    },
    addAllocation(item, index) {
      let list = this.form.evaluationConfigTaskList;
      console.log('list', list)
      let length = list.length - 1;
      let currentItem = list[length];
      console.log('currentItem', currentItem)
      if (currentItem.planStartTime && currentItem.planEvaluationNum) {
        // let newList = [], newData = {
        //   planStartTime: "",
        //   planEvaluationNum: ''
        // };
        this.form.evaluationConfigTaskList.push({
          planStartTime: "",
          planEvaluationNum: ''
        })
        // this.$set(this.form.evaluationConfigTaskList, index + 1, newData)
        // this.$forceUpdate();
        console.log('@@@@@@@@', this.form.evaluationConfigTaskList)
      } else {
        this.$message.error('请先完善测评时间或测评单数！');
      }
    },
    cutAllocation(item, index) {
      let list = this.form.evaluationConfigTaskList;
      let length = list.length;
      this.form.evaluationConfigTaskList.splice(index, 1)
    },
    // 获取测评配置详情
    getConfigDetail() {
      let message = this.evaluationType == '5' ? '整体测评' : this.evaluationType == '51' ? '单品测评' : "指定日期测评"
      this.title = "修改" + message + "配置"
      let data = {
        id: this.configId,
        type: this.evaluationType
      }
      selectEvaluationConfig(data).then(res => {
        let data = res.data
        // let dateList = []
        // dateList.push(data.startTime)
        // dateList.push(data.endTime)
        // for (let key in data) {
        //   if (data[key] != null) {
        //     data[key] = '' + data[key]
        //   }
        // }
        data.evaluationConfigTaskList = [];
        if (data.sort) {
          let sortList = data.sort.split(',');
          for (let i = 0; i < sortList.length; i++) {
            this.storeSortData['storeSort' + i] = sortList[i]
          }
        }
        this.form = data
        this.form.evaluationCountry = this.form.evaluationCountry.split(',')
        this.form.isEvaluation = data.isEvaluation == '0' ? false : true
        this.form.randomRemark = data.randomRemark.toString()
        if (this.isUseShareCode == '1') {
          this.form.evaluationConfigTaskList = [{
            planStartTime: data.planStartTime,
            planEvaluationNum: data.planEvaluationNum,
          }]
        }
      })
    },
    // 单品测评条件1校验
    multipllCheck1(rule, value, callback) {
      let value2 = this.form.orderQuantity
      if (!value2) {
        callback(new Error("单品测评条件1不能为空！"));
      } else {
        this.$Validate.isPositiveInteger(rule, value, callback)
      }
    },
    // 店铺测评条件3 最大值最小值
    multipllCheck2(rule, value, callback) {
      let value2 = this.form.amountMin
      value2 = Number(value2)
      value = Number(value)
      if (value) {
        if (value < value2) {
          callback(new Error("最大金额不能小于最小金额！"));
        }
        if (value == value2) {
          callback(new Error("最大金额不能等于最小金额！"));
        }
      }
      this.$Validate.isPositiveInteger(rule, value2, callback)
    },
    // 选择测评时间
    chooseEvaluationTime(e) {
      console.log('eeeee', e)
      // this.form.startTime = e[0]
      // this.form.endTime = e[1]
    },
    reset() {
      this.form = {
        evaluationName: undefined,
        evaluationCountry: undefined,
        sort: "",
        openTime: undefined,
        orderQuantity: undefined,
        afterNumber: undefined,
        isEvaluation: true,
        beforeDay: undefined,
        amountMax: undefined,
        amountMin: undefined,
        startTime: undefined,
        endTime: undefined,
        storeId: this.storeId,
        storeUserName: this.storeUserName,
        userId: this.userId,
        randomRemark: '1',//是否开启随机备注
        shieldProductIds: undefined,
        evaluationMonthMax: undefined,
        evaluationDayMax: undefined,
        evaluationConfigTaskList: [{
          planStartTime: "",
          planEvaluationNum: ''
        }],
        evaluationType: "5",
        nullOrderDay: undefined,
        status: "1"
      }
      this.resetForm("form");
    },
    // 获取品牌选择列表
    getBrandList() {
      getBrand().then(res => {
        this.brandList = res.data
      });
    },
    // 确定提交
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$confirm('是否确定提交当前测评配置计划内容？', '提示').then(() => {
            this.form.evaluationType = this.evaluationRadio
            this.form.isEvaluation = this.form.isEvaluation ? '1' : '0'
            this.form.evaluationCountry = this.form.evaluationCountry.toString()
            for (let key in this.storeSortData) {
              this.form.sort += this.storeSortData[key] + ','
            }
            if (this.isUseShareCode == '1') {
              this.form.id = undefined;
              this.form.storeId = this.storeId
              this.form.userId = this.userId
              this.form.storeUserName = this.storeUserName
            }
            if (this.form.sort) {
              this.form.sort = this.form.sort.slice(0, this.form.sort.length - 1)
            }
            saveEvaluationConfig(this.form).then(res => {
              this.$message.success(res.msg)
              this.cancel()
            })
          })
        }
      })
    },
    // 取消
    cancel() {
      this.$emit('close', false)
    },
  }
}
</script>

<style scoped>

</style>
